package com.binhai.user;

import com.alibaba.fastjson.JSON;
import com.binhai.db.SpringDB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * WebServlet注解(约定)，映射路径为/UserServlet
 */
@Component
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    //自动加载springDB对象
    @Autowired
    private SpringDB springDB;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //操作码
        String op = request.getParameter("op");
        if (op.equals("add")){
            saveInfo(request, response);
        }else if(op.equals("delete")){//删除
            //获取id参数
            String id = request.getParameter("id");
            deleteInfo(response,id);
        }else if(op.equals("selectByWhere")){//条件查询
            //获取id参数
            String name = request.getParameter("name");
            selectByWhere(response,name);
        }else if(op.equals("selectById")){//根据id查询用户信息
            //获取id参数
            String id = request.getParameter("id");
            selectById(response,id);
        }else if(op.equals("modify")){//修改用户信息
            modifyInfo(request,response);
        }else{
            //查询所有用户
            selectAllInfos(response);
        }


    }

    private void modifyInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map map = new HashMap();
        try {
            JdbcTemplate jdbcTemplate = springDB.getJdbcTemplate();
            String sql = "update t_user set name='"+request.getParameter("name")+"',pass='"+request.getParameter("pass")+"',tel='"+request.getParameter("tel")+"',beizhu='"+request.getParameter("beizhu")+"' where id="+request.getParameter("id");
            jdbcTemplate.execute(sql);
            map.put("result", "success");
        }
        catch (Exception e){
            e.printStackTrace();
            map.put("result", "error");
        }
        String s = JSON.toJSONString(map);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(s);
    }

    private void selectById(HttpServletResponse response, String id) {
        try {
            JdbcTemplate jdbcTemplate = springDB.getJdbcTemplate();
            String sql = "select * from t_user where id="+id;
            Map map = jdbcTemplate.queryForMap(sql);
            String s = JSON.toJSONString(map);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(s);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    private void selectByWhere(HttpServletResponse response, String name) {
        try {
            JdbcTemplate jdbcTemplate = springDB.getJdbcTemplate();
            String sql = "select * from t_user where name like '%"+name+"%' and state=0";
            List list = jdbcTemplate.queryForList(sql);
            String s = JSON.toJSONString(list);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(s);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    private void deleteInfo(HttpServletResponse response, String id) throws IOException {
        Map map = new HashMap();
        try {
            JdbcTemplate jdbcTemplate = springDB.getJdbcTemplate();
            String sql = "update t_user set state=1 where id="+id;
            jdbcTemplate.execute(sql);
            map.put("result", "success");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "error");
        }
        String s = JSON.toJSONString(map);
        response.getWriter().write(s);
    }

    //保存用户信息
    private void saveInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取name、pass、tel、beizhu参数
        String name = request.getParameter("name");
        String pass = request.getParameter("pass");
        String tel = request.getParameter("tel");
        String beizhu = request.getParameter("beizhu");
        Map map = new HashMap();
        //将name、pass、tel、beizhu等字段插入到t_user表
        try {
            JdbcTemplate jdbcTemplate = springDB.getJdbcTemplate();
            String sql = "insert into t_user(name,pass,tel,beizhu) values('" + name + "','" + pass + "','" + tel + "','" + beizhu + "')";
            jdbcTemplate.execute(sql);

            map.put("result", "success");

        } catch (Exception ex) {
            ex.printStackTrace();
            map.put("result", "error");
        }
        String s = JSON.toJSONString(map);
        response.getWriter().write(s);
    }

    /**
     * 查询所有用户信息
     * @param response
     */
    private void selectAllInfos(HttpServletResponse response) {
        try {
            JdbcTemplate jdbcTemplate = springDB.getJdbcTemplate();
            String sql = "select * from t_user where  state=0";
            //使用模版查询，返回list列表
            List list = jdbcTemplate.queryForList(sql);
            //map转成JSON字符串
            String s = JSON.toJSONString(list);
            //响应数据
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(s);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //

}
